package com.zhihaoliang.moshi.biz.io

import android.content.Context
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.zhihaoliang.moshi.biz.models.Plant
import com.zhihaoliang.moshi.util.log
import com.zhihaoliang.moshi.util.logJson
import kotlinx.coroutines.coroutineScope
import okio.buffer
import okio.source

/**
 * @author 支豪亮
 * @date 2023/1/20 15:28
 * @des 流的解析
 */

suspend fun inputStream(context: Context){
    coroutineScope {
        try {
            val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()

            val inputStream = context.assets.open("plants.json")

            val plantListType = Types.newParameterizedType(List::class.java, Plant::class.java)
            val plantListAdapter = moshi.adapter<List<Plant>>(plantListType)

            val plantList = plantListAdapter.fromJson(inputStream.source().buffer()) ?: emptyList()
            logJson<List<Plant>>(plantList,plantListAdapter)
        }catch (e:Exception){
           log("数据流解析失败")
        }
    }

}